package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.entities.beans.page.BindVariable;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.customWidget.CheckWidgetCmd;
import cn.easyplatform.studio.cmd.customWidget.SaveWidgetCmd;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.CustomWidgetVo;
import cn.easyplatform.studio.vos.DeviceVo;
import cn.easyplatform.studio.web.editors.Editor;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import cn.easyplatform.studio.web.editors.support.ZulXsdUtil;
import cn.easyplatform.web.ext.cmez.CMeditor;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.*;
import sun.misc.BASE64Encoder;

import java.util.List;

public class CustomWidgetSetView extends AbstractView<CustomWidgetVo> {
    BASE64Encoder encoder = new BASE64Encoder();//编码

    private Iframe iframe;
    private Label msgLabel;
    private CMeditor code;
    private Textbox name;
    private Textbox desp;
    private Button variableBtn;
    private Button cssBtn;
    private Button scriptBtn;
    private Image pic;

    private CustomWidgetVo customWidgetVo;
    private String base64String;

    protected CustomWidgetSetView(EditorCallback<CustomWidgetVo> cb) {
        super(null, cb);
        if (cb != null)
            customWidgetVo = cb.getValue();
    }

    @Override
    protected void createContent(Component parent) {
        Executions.createComponents("~./include/help/CustomWidget.zul", parent, null);
        iframe = (Iframe) parent.getFellow("custom_iframe_content");
        msgLabel = (Label) parent.getFellow("custom_label_msg");
        parent.getFellow("custom_button_format").addEventListener(Events.ON_CLICK, this);
        code = (CMeditor) parent.getFellow("custom_cmeditor_code");
        code.addEventListener(Events.ON_CHANGING, this);
        name = (Textbox) parent.getFellow("custom_textbox_name");
        desp = (Textbox) parent.getFellow("custom_textbox_desp");
        variableBtn = (Button) parent.getFellow("custom_button_variable");
        variableBtn.addEventListener(Events.ON_CLICK, this);
        if (customWidgetVo.getDevice() != null && customWidgetVo.getDevice().getBindVariables() != null &&
                customWidgetVo.getDevice().getBindVariables().size() > 0)
            variableBtn.setSclass("epeditor-btn-mark");
        cssBtn = (Button) parent.getFellow("custom_button_css");
        cssBtn.addEventListener(Events.ON_CLICK, this);
        if (customWidgetVo.getDevice() != null && Strings.isBlank(customWidgetVo.getDevice().getStyle()) == false) {
            cssBtn.setSclass("epeditor-btn-mark");
        }
        scriptBtn = (Button) parent.getFellow("custom_button_script");
        scriptBtn.addEventListener(Events.ON_CLICK, this);
        if (customWidgetVo.getDevice() != null && Strings.isBlank(customWidgetVo.getDevice().getJavascript()) == false) {
            scriptBtn.setSclass("epeditor-btn-mark");
        }
        pic = (Image) parent.getFellow("custom_image_pics");
        parent.getFellow("custom_button_image_upload").addEventListener(Events.ON_UPLOAD, this);
        parent.getFellow("custom_dropupload_pic").addEventListener(Events.ON_UPLOAD, this);
        parent.getFellow("custom_button_save").addEventListener(Events.ON_CLICK, this);
        Window window = (Window) parent.getParent().getParent();
        window.setWidth("930px");
    }

    private void redraw() {
        String content = (String) code.getValue();
        if (!Strings.isBlank(content)) {
            StringBuilder sb = new StringBuilder();
            sb.append("<?taglib uri=\"http://www.zkoss.org/dsp/web/core\" prefix=\"c\"?>\n");
            sb.append("<div hflex=\"1\" vflex=\"1\">");
            if (customWidgetVo.getDevice() != null) {
                if (Strings.isBlank(customWidgetVo.getDevice().getStyle()) == false) {
                    sb.append("<style content=\"");
                    sb.append(customWidgetVo.getDevice().getStyle());
                    sb.append("\"/>");
                }
                if (Strings.isBlank(customWidgetVo.getDevice().getJavascript()) == false) {
                    sb.append("<script content=\"");
                    sb.append(customWidgetVo.getDevice().getJavascript());
                    sb.append("\"/>");
                }
            }
            sb.append(content);
            sb.append("</div>");
            content = sb.toString();
            try {
                //验证代码格式
                Div div = new Div();
                Executions.createComponentsDirectly(content,
                        "zul", div, null);

                CodeFormatter.formatXML(ZulXsdUtil
                        .buildDocument(content));
                iframe.getDesktop().getSession().setAttribute("content", content);
                String srcPath = "/richlet/dyamic?compose=content&s=" + System.currentTimeMillis();
                iframe.setSrc(srcPath);
                msgLabel.setValue("");
            } catch (Exception ex) {
                String msg = ex.getMessage();
                if (msg != null) {
                    int idx = msg.indexOf("for class");
                    if (idx > 0)
                        msg = msg.substring(0, idx);
                    else if ((idx = msg.indexOf("SAXParseException;")) >= 0) {
                        msg = msg.substring(idx + 18);
                    }
                } else
                    msg = "Wrong page content";
                msgLabel.setValue(msg);
            }
        }
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getName().equals(Events.ON_UPLOAD)) {
            UploadEvent evt = (UploadEvent) event;
            org.zkoss.util.media.Media media = evt.getMedia();
            if (evt.getTarget().getId().equals("custom_button_image_upload") || evt.getTarget().getId().equals("custom_dropupload_pic")) {
                if (media instanceof org.zkoss.image.Image) {
                    org.zkoss.image.Image img = (org.zkoss.image.Image) media;
                    pic.setStyle("border:3px dashed #e6e6e6;border-radius:10px;display: inline;justify-content:center;align-items:Center;max-height: 250px;max-width: 250px;");
                    pic.setContent(img);

                    base64String = encoder.encode(media.getByteData());
                } else {
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
        } else if (event.getTarget().equals(code) ) {
            redraw();
        } else if (event.getTarget().getId().equals("custom_button_format")) {
            String value = (String) code.getValue();
            if (!Strings.isBlank(value))
                code.exeCmd("formatAll");
        } else if (event.getTarget().equals(variableBtn)) {
            AbstractView.createBindVariable(new EditorCallback<List<BindVariable>>() {
                @Override
                public List<BindVariable> getValue() {
                    if (customWidgetVo.getDevice() != null)
                        return customWidgetVo.getDevice().getBindVariables();
                    return null;
                }

                @Override
                public void setValue(List<BindVariable> value) {
                    if (customWidgetVo.getDevice() == null)
                        customWidgetVo.setDevice(new DeviceVo());
                    customWidgetVo.getDevice().setBindVariables(value);
                    if (value == null || value.size() == 0) {
                        variableBtn.setSclass("epeditor-btn");
                    } else {
                        variableBtn.setSclass("epeditor-btn-mark");
                    }
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("entity.page.variable");
                }

                @Override
                public Page getPage() {
                    return event.getTarget().getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, event.getTarget()).doOverlapped();
        } else if (event.getTarget().equals(scriptBtn)) {
            AbstractView.createCodeView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    if (customWidgetVo.getDevice() != null)
                        return customWidgetVo.getDevice().getJavascript();
                    else
                        return null;
                }

                @Override
                public void setValue(String value) {
                    if (customWidgetVo.getDevice() == null)
                        customWidgetVo.setDevice(new DeviceVo());
                    customWidgetVo.getDevice().setJavascript(value);
                    if (Strings.isBlank(value)) {
                        scriptBtn.setSclass("epeditor-btn");
                    } else {
                        scriptBtn.setSclass("epeditor-btn-mark");
                    }
                }

                @Override
                public String getTitle() {
                    return "javascript";
                }

                @Override
                public Page getPage() {
                    return scriptBtn.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            },"javascript", scriptBtn).doOverlapped();
        } else if (cssBtn.equals(event.getTarget())) {
            AbstractView.createCodeView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    if (customWidgetVo.getDevice() != null)
                        return customWidgetVo.getDevice().getStyle();
                    else
                        return null;
                }

                @Override
                public void setValue(String value) {
                    if (customWidgetVo.getDevice() == null)
                        customWidgetVo.setDevice(new DeviceVo());
                    customWidgetVo.getDevice().setStyle(value);
                    if (Strings.isBlank(value)) {
                        cssBtn.setSclass("epeditor-btn");
                    } else {
                        cssBtn.setSclass("epeditor-btn-mark");
                    }
                }

                @Override
                public String getTitle() {
                    return "style";
                }

                @Override
                public Page getPage() {
                    return cssBtn.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            },"css", cssBtn).doOverlapped();
        } else if ("custom_button_save".equals(event.getTarget().getId())) {
            if (Strings.isBlank(name.getValue())) {
                throw new WrongValueException(name, Labels
                        .getLabel("entity.name"));
            }
            if (Strings.isBlank(code.getValue().toString())) {
                throw new WrongValueException(code, Labels
                        .getLabel("menu.code"));
            }
            customWidgetVo.setWidgetName(name.getValue().trim());
            customWidgetVo.setWidgetDesp(desp.getValue().trim());
            customWidgetVo.setWidgetPic(base64String);
            customWidgetVo.setContent(code.getValue().toString());
            //验证名称重复
            String error = StudioApp.execute(new CheckWidgetCmd(customWidgetVo));
            if (error != null) {
                WebUtils.showError(error);
                return;
            }
            //是否操作成功
            Boolean upflag = StudioApp.execute(new SaveWidgetCmd(customWidgetVo));
            if (upflag) {
                WebUtils.showSuccess(Labels.getLabel("button.save"));
            }
        }
    }
}
